<?php

namespace app\index\controller;

use think\exception\ValidateException;
use app\model\Users;
use app\model\UuidRelation;
use app\model\Openid;

class LoginController extends Base
{
	//用户登录
	public function index()
	{
		$data = only('username,password');

		if (empty($data['username'])) {
			throw new ValidateException('请输入用户名');
		}

		if (empty($data['password'])) {
			throw new ValidateException('请输入密码');
		}

		$ptype = input('post.ptype');
		$res = $this->checkLogin($data);
		if ($res) {
			$this->userInfo['uuid'] = $res['uuid'];
			$this->setToken($this->userInfo, $this->getToken());

			if($res['id']==1){
                $openid  = '12345sadfgdfggh';
            }else{
			    $openid  = getFans()['openid'];
            }
			Openid::create(['weid' => weid(), 'uuid' => $res['uuid'], 'ptype' => $ptype, 'openid' => $openid]);
			UuidRelation::create(['weid' => weid(), 'uuid' => $res['uuid'], 'uid' => UID()]);

			return $this->json(['msg' => '登录成功', 'data' => $res]);
		}
	}

	//验证登录
	private function checkLogin($data)
	{
		$where['username'] = $data['username'];
		$field = 'id,weid,uuid,uid,sid,title,username,password,salt,create_time,status';
		$info =	Users::field($field)->where($where)->find();

		if ($info) {
			$info = $info->toArray();
			if ($info['password'] === pass_hash($data['password'], $info["salt"])) {
				unset($info['password']);
				unset($info["salt"]);

				if (empty($info['uuid'])) {
					$info['uuid'] = uniqid(rand(1, 10000));
					Users::where('id', $info['id'])->update(['uuid' => $info['uuid']]);
				}

				if (!($info['status'])) {
					throw new ValidateException("该账户被禁用");
				}
			} else {
				throw new ValidateException("用户名或者密码不正确");
			}
		} else {
			throw new ValidateException("用户名不存在");
		}

		return $info;
	}
}
